<template>
    <div>
        <div class="searchArea">
            <el-input v-model="envName" placeholder="环境名称" class="searchTextInput" clearable/>
            <el-input v-model="groupId" placeholder="分组名" class="searchTextInput" clearable/>
            <el-button type="primary" class="searchButton" @click="loadData">查询</el-button>
            <div class="addTaskArea">
                <el-button type="primary" class="importButton" @click="isShowImportEnvDialog = true" plain>导入</el-button>
                <el-button type="primary" class="exportButton1" plain @click="exportEnable=true" v-if="exportEnable == false">导出</el-button>
                <el-button type="primary" class="exportButton2" @click="exportAction" v-if="exportEnable">导出已选择项</el-button>
                <el-button type="primary" class="cancelExportButton" @click="exportEnable = false" plain v-if="exportEnable">取消导出</el-button>
                <el-button type="primary" class="searchButton" @click="gotoCreateEnv" plain>新增</el-button>
            </div>
        </div>
        <div class="searchArea">
            <el-form-item label="">
                <el-tag
                    v-for="tag in tagIds"
                    :key="tag"
                    class="mx-1 filterTag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                >
                    {{ tag }}
                </el-tag>
                <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="tagInput"
                    size="small"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                    <el-icon size="10" color="black" style="margin-right:5px;">
                        <Filter />
                    </el-icon>
                    添加标签
                </el-button>
            </el-form-item>
        </div>
        <div class="table">
            <el-table 
            :data="tableData" 
            style="width: 100%" 
            max-height="500"
            stripe 
            border 
            :cell-style="{textAlign:'center'}"
            :header-cell-style="{textAlign:'center'}"
            @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" v-if="exportEnable"/>
                <el-table-column prop="id" label="ID" width="50" />
                <el-table-column prop="envID" label="环境ID" width="150">
                    <template #default="scope">
                        <div style="user-select:text ;">
                            <el-tooltip
                                raw-content
                                class="box-item"
                                popper-class="idtip"
                                effect="dark"
                                :content="getToolTipContent(scope.row.envID)"
                                placement="top"
                                style="user-select:text ;"
                            >
                                <div class="IDStr">{{scope.row.envID}}</div>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="envName" label="环境名称" min-width="88" max-width="150"/>
                <el-table-column prop="groupID" label="分组名" width="88" :formatter="formatGroupName"/>
                <el-table-column prop="tagIDs" label="标签" width="100" :formatter="getTagName">
                    <template #default="scope">
                        <div v-if="scope.row.tagIDs == ''">/</div>
                        <div v-else>
                            <el-tag class="tag" v-for="item in scope.row.tagIDs.split(',')" v-bind:key="item">{{ getTagName(item) }}</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="createAccount" label="创建人" width="88"/>
                <el-table-column prop="mark" label="备注" min-width="100"/>
                <el-table-column prop="createTime" label="创建时间" width="155" :formatter="formatTime"/>
                <el-table-column prop="morder" label="排序" width="88"/>
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClickStart(scope.row)" v-if="!isChromeOpened(scope.row.envID)"
                        >打开</el-button>
                        <el-button link type="primary" size="small" @click="handleClickStop(scope.row)" v-if="isChromeOpened(scope.row.envID)"
                        >关闭</el-button>
                        <el-button link type="primary" size="small" @click="handleClickEdit(scope.row)" style="margin-left: 0px;"
                        >编辑</el-button>
                        <el-button link type="primary" size="small" @click="handleClickDel(scope.row)" style="margin-left:0px;"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100, 150, 200, 250, 300]"
                :small="false"
                :disabled="false"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="loadData"
                @current-change="loadData"
                total-text="总共"
                style="justify-content:end"
            />
        </div>
        <ImportEnvDialog v-if="isShowImportEnvDialog" v-model:isShow="isShowImportEnvDialog" :handleUpdated="loadData"></ImportEnvDialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed,watch,nextTick} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import EnvApi from '../../../apis/env';
import { Filter } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElInput} from 'element-plus'
import { saveAs } from 'file-saver';
import dayjs from 'dayjs'
import ImportEnvDialog from './ImportEnvDialog.vue';
import {formatTime} from '../../../utils/TimeUtils'

var tableData:any = ref([])
const currentPage = ref(0)
const pageSize = ref(10)
const total = ref(200)
const envName = ref("")
const groupId = ref("")
const selectedData = ref();
const isShowImportEnvDialog = ref(false);
const tagIds = ref<Array<string>>([]);
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
const exportEnable = ref(false);
const openedEnvIDs = ref([])

const router = useRouter();
const route = useRoute();

console.log('[EnvMgr]Route', route.path);

let tags:any = [];
let groups:any = [];

const loadData = ()=>{
    EnvApi.fetchEnvTag("", 0, 999).then(ret=>{
        if(ret.code == 0){
            tags = ret.data.list;
        }
        return EnvApi.fetchEnvGroup("", 0, 999);
    }).then(ret=>{
        if(ret.code == 0){
            groups = ret.data.list;
        }
        return EnvApi.fetchEnv(envName.value, groupId.value, tagIds.value,currentPage.value, pageSize.value);
    }).then(ret=>{
        console.log('[RPAEnvMgr]', ret);
        tableData.value = ret.data.list;
        total.value = ret.data.totalCount;
        currentPage.value = ret.data.page;
        pageSize.value = ret.data.pageSize;
    }).catch(err=>{
        console.log('[RPAEnvMgr]', err);
    })
}

onMounted(()=>{
    console.log('[RPAEnvMgr] onMounted');
    loadData();

    // 主动从主线程获取已经打开的环境
    try{
        let ret = (window as any).ipcRenderer.sendSync('execute_env', {"action":"getOpenedEnvs", "data":""});
        console.log('getOpenedEnvs', ret);
        openedEnvIDs.value = ret;
    }catch(err){
        console.log('getOpenedEnvs err', err);
    }

    // 监听从主线程发送过来的事件。
    try{
        console.log('ipcRenderer on updateOpenedEnvIDs');
        (window as any).ipcRenderer.on('updateOpenedEnvIDs', async (event:any, arg:any)=>{
            console.log("updateOpenedEnvIDs", arg);
            openedEnvIDs.value = arg;
        })
    }catch(err){
    }
    
})

const handleClickEdit = (row:any)=>{
    console.log('编辑', row);
    router.push('/env/envMgr/editEnv/'+row.id);
}

const handleClickDel = (row:any) => {
    console.log('删除', row);
    // 二次确认
    ElMessageBox.confirm(`确认删除租户${row.envName}吗?`,'温馨提示',
        {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        }
    ).then(() => {
        let id = row.id;
        return EnvApi.delEnv(id);
    }).then(ret=>{
        loadData();
        ElMessage({
            type: 'success',
            message: "删除成功",
        })
    }).catch((err) => {
        if(err=="cancel"){
            ElMessage({
                type: 'info',
                message: "取消删除操作",
            })
        }else{
            ElMessage({
                type: 'error',
                message: "删除失败",
            })
        }
    })

}

const handleClose = (tag: string) => {
  tagIds.value.splice(tagIds.value.indexOf(tag), 1)
  loadData();
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    tagIds.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
  loadData();
}

const getTagName = (tagID:any)=>{
    let filterTags = tags.filter((item:any)=>item.tagID == tagID);
    if(filterTags && filterTags.length>0){
        return filterTags[0].tagName;
    }else{
        return "未知标签";
    }
} 

const formatGroupName = (row:any, column:any, cellValue:any, index:any)=>{
    let filterGroup = groups.filter((item:any)=>item.groupID == cellValue);
    if(filterGroup && filterGroup.length>0){
        return filterGroup[0].groupName;
    }else{
        return "未知分组";
    }
}

const gotoCreateEnv = ()=>{
    router.push("/env/envMgr/createEnv")
}

const handleClickStart = (row:any)=>{
    console.log('ipcRenderer', (window as any).ipcRenderer, window);
    try {
        (window as any).ipcRenderer.send('execute_env', {"action":"openChrome", "data":JSON.stringify(row)});
        // setTimeout(() => {
        //     loadData();
        // }, 3000);
    } catch (error) {
        console.warn("[RPATaskMgr]未运行在Electron项目中。",error);
    }
}

const handleClickStop = (row:any)=>{
    console.log('ipcRenderer', (window as any).ipcRenderer, window);
    try {
        (window as any).ipcRenderer.send('execute_env', {"action":"closeChrome", "data":JSON.stringify(row)});
        // setTimeout(() => {
        //     loadData();
        // }, 3000);
    } catch (error) {
        console.warn("[RPATaskMgr]未运行在Electron项目中。",error);
    }
}

const exportAction = ()=>{
    // 导出选中的行
    EnvApi.exportEnv(selectedData.value).then(ret=>{
        if(ret.code == 0){
            ElMessage({
                type: 'success',
                message: "导出成功",
            })
            // 生成下载文件
            let time = dayjs().format("YYYY-MM-DDTHH:mm:ss");
            var file = new File([JSON.stringify(ret.data, null, 2)], "export-"+time+".json", {type: "application/json;charset=utf-8"});
            saveAs(file);

        }else{
            ElMessage({
                type: 'error',
                message: "导出失败",
            })
        }
        exportEnable.value = false;
    }).catch(err=>{
        ElMessage({
            type: 'error',
            message: err,
        })
        exportEnable.value = false;
    })

}

const handleSelectionChange = (row: any)=>{
    console.log("select row", row);
    const ids = row.map((item:any)=>item.id);
    selectedData.value = ids;
    console.log("select row ids", ids);
}

const isChromeOpened = (envID:any)=>{
   return openedEnvIDs.value.indexOf(envID as never) >= 0;
}

const getToolTipContent = (envID:any)=>{
    return "<div style='user-select: text;'>" + envID +"</div>";
}
</script>

<style scoped>
.pagination {
    margin-top: 15px;
}
.searchArea, .oeprations {
    padding-bottom: 10px;
    display: flex;
}
.searchButton {
    margin-left: 0px;
}
.searchTextInput {
    width: 120px;
    margin-right: 10px;
}
.operationButton {
    margin-right: 0px;
}
.filterTag {
    margin-right: 5px;
}
.tagInput {
    width: 100px;
}

.addTaskArea {
    display: inline-flex;
    position: absolute;
    right: 20px;
}
.exportButton1 {
    margin-right: 5px;
    margin-left: 5px;
}
.exportButton2 {
    margin-right: 0px;
    margin-left: 5px;
}

.cancelExportButton {
    margin-right: 5px;
    margin-left: 5px;
}
.importButton{
    margin-right: 0px;
}
.tag {
    margin-top: 5px;
}
.IDStr {
    text-overflow:ellipsis; 
    width: 130px;
    overflow:hidden;
    white-space:nowrap;
}
</style>
